package com.chj.setmsg;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消息的属性的控制
 */
public class ReplyToConsumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("10.200.169.5");
        connectionFactory.setVirtualHost("chj_vhost");
        connectionFactory.setUsername("chj");
        connectionFactory.setPassword("123456");
        // 创建连接
        Connection connection = connectionFactory.newConnection();
        // 创建信道
        final Channel channel = connection.createChannel();
        // 创建交换器 BuiltinExchangeType.DIRECT == direct
        channel.exchangeDeclare(ReplyToProducer.EXCHANGE_NAME,"direct",false);
        // 声明一个队列
        String queueName = "replyto";
        channel.queueDeclare(queueName,false,false,false,null);
        //日志消息级别，作为路由键使用
        String routekey = "error";
        channel.queueBind(queueName,ReplyToProducer.EXCHANGE_NAME,routekey);
        System.out.println("waiting for message........");
        // 声明了一个消费者
        final Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag,Envelope envelope,AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println("Consumer Received [ "+envelope.getRoutingKey()+" ] "+message);
                //TODO 从消息中拿到相关属性（确定要应答的消息ID,）
                AMQP.BasicProperties respProp = new AMQP.BasicProperties.Builder()
                        .replyTo(properties.getReplyTo())
                        .correlationId(properties.getMessageId()).build();
                //TODO 消息消费时，同时需要生作为生产者生产消息（以OK为标识）
                channel.basicPublish("", respProp.getReplyTo(), respProp,
                        (", I am OK, "+message).getBytes("UTF-8"));
            }
        };
        // 消费者正式开始在指定队列上消费消息
        channel.basicConsume(queueName,true,consumer);
    }
}
